import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
// import ZoomImg from 'react-zoomimg';
import {WX_MP_APP_ID, WEB_DOMAIN} from '../../../utils/constants';
// import { PinchView } from 'react-pinch-zoom-pan';
import { Icon, message } from 'antd';
import Protocol from '../Protocol/Protocol';
import API from '../../../api/share';
import './FileShareMobile.scss';
import Application from "../../components/Application/index";
import InvalidComponet from "../../components/invaildComponent/invalidComponent";

const classNames = require('classnames');

class FileShareMobile extends Component {
    constructor () {
        super();
        this.state = {
            sharedBy: '',
            title: '给您分享了一个文件',
            password: '',
            radioChecked: false,
            errorMessage: '密码输入错误',
            errorMessageVisible: false,
            showViewer: false,
            backViewer:true,
            wrapperViewer:true,
            imagelist: [],
            protocolVisible: false,
            passwordVisible: false,
            radioVisible: false,
            shareId: '',
            nickName: '',
            telphone:'',
            nickTitleName:'',
            invalidPass:false,
            loadingComplete:false,
        };
        this.handleView = this.handleView.bind(this);
        this.changeProtocol = this.changeProtocol.bind(this);
        this.closeImageView = this.closeImageView.bind(this);
        this.handleProtocol = this.handleProtocol.bind(this);
        this.toogleProtocol = this.toogleProtocol.bind(this);
        this.initCheck = this.initCheck.bind(this);
        this.showPicture = this.showPicture.bind(this);
    }
    componentWillReceiveProps () {
    }
    componentWillMount () {
        const { shareId, sharedBy } = this.props.match.params;
        var code = null;
        if (this.props.location.search.indexOf('code=') > -1) {
          code = this.props.location.search.split('&')[0].split('=')[1];
          // alert(code);
        }
        this.setState({
            shareId,
            sharedBy,
            code,
        });
    }
    componentDidMount () {
        // alert(window.location.href);
        this.recalc();
        this.initCheck();
    }
    recalc () {
        (function (doc, win) {
            const docEl = doc.documentElement;
            const resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
            const recalc = function () {
                const { clientWidth } = docEl;
                if (!clientWidth) return;
                docEl.style.fontSize = `${100 * (clientWidth / 750)}px`;
            };
            if (!doc.addEventListener) return;
            win.addEventListener(resizeEvt, recalc(), false);
            doc.addEventListener('DOMContentLoaded', recalc(), false);
        }(document, window));
    }
    wechatLogin = async () => {
        const { code } = this.state;
        const visitBy = this.props.location.pathname.indexOf('fileShareMobile') >= 0 ? 'mobile' : 'web';
        const response = await API.wechatLogin({ code, visitBy });
        console.log(response);
        const responseCode = response.code;
        const { data } = response;
        if (responseCode === 1) {
            const { accessToken, refreshToken } = data;
            window.localStorage.setItem('accessToken', accessToken);
            window.localStorage.setItem('refreshToken', refreshToken);
            this.loadFile();
        } else {
            // message.error('微信授权登录失败');
        }
    }
    loadFile = async () => {
        const { shareId, sharedBy } = this.state;
        const params = {
            shareId,
            sharedBy,
        };
        const response = await API.viewShare(params);
        console.log(response);
        const { code, data } = response;
        if(data.link.valid == false){
            this.setState({
              invalidPass:true
            });
         }else{
            if (code === 1) {
                const { items } = data.version;
                const phone  = data.contacter;
               const shared = data.sharedBy;
                const nickName = data.nickname;
                this.setState({
                    telphone:phone,
                    sharedBy:shared,
                    nickTitleName:nickName,
                });
                this.timer = setInterval(
                    () => {
                       this.refreshFlie().then((res)=>{
                           const code = res;
                        if (code === 1) {
                            this.showPicture(items);
                        }else{
                            this.setState({
                                loadingComplete:true,
                            });
                        }
                       })  
                    },
                    3000
                );  
            } else if (code === 21018 || code === 21037) {
                const { hasPassword, signed, ownerNickname } = data;
                this.setState({
                    passwordVisible: hasPassword,
                    radioVisible: !signed,
                    nickName: ownerNickname,
                });
            }
         }
    }
    async initCheck () {
        const accessToken = window.localStorage.getItem('accessToken');
        const { code } = this.state;
        const { shareId, sharedBy } = this.state;
        if (!code || code === '') {
            if(accessToken) {
                this.loadFile();
            }else{
                // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WX_MP_APP_ID}&redirect_uri=${WEB_DOMAIN}/fileShareMobile/${shareId}/${sharedBy}&response_type=code&scope=snsapi_userinfo#wechat_redirect`;
            }
        } else {
            // this.wechatLogin();
        }
    }
    changePassword (e) {
        this.setState({
            password: e.target.value,
        });
    }
    changeProtocol () {
        this.setState({
            radioChecked: !this.state.radioChecked,
        });
    }
    hideErrorMessage () {
        setTimeout(() => {
            this.setState({
                errorMessageVisible: false,
            });
        }, 3000);
    }
    showPicture (items) {
        const pictures = [];
        items.forEach((item) => {
            pictures.push(item.url);
        });
        this.setState({
            showViewer: true,
            backViewer:false,
            protocolVisible: false,
            wrapperViewer:false,
            imagelist: pictures,
        });
    }
    async handleView () {
        const {
            shareId, sharedBy, password,
            radioChecked, passwordVisible, radioVisible,
        } = this.state;
        if (passwordVisible && !password) {
            this.setState({
                errorMessage: '请输入密码！',
                errorMessageVisible: true,
            });
            this.hideErrorMessage();
            return;
        }
        if (radioVisible && !radioChecked) {
            this.setState({
                errorMessage: '请同意保密协议！',
                errorMessageVisible: true,
            });
            this.hideErrorMessage();
            return;
        }
        const isSigned = !radioVisible ? !radioVisible : radioChecked;
        const params = {
            shareId,
            sharedBy,
            password,
            isSigned,
        };
        const response = await API.viewShare(params);
        const { code } = response;
        if (code === 1) {
            const { items } = response.data.version;
            const phone = response.data.contacter;
            const shared =  response.data.sharedBy;
            const nickName =  response.data.nickname;
            this.setState({
                telphone:phone,
                nickTitleName:nickName
            });
            this.showPicture(items);
        } else if (code === 21018) {
            this.setState({
                errorMessage: '密码输入错误！',
                errorMessageVisible: true,
            });
            this.hideErrorMessage();
        }
    }
    handleProtocol (e) {
        e.preventDefault();
        this.setState({
            protocolVisible: true,
        });
    }
    closeImageView () {
        this.setState({
            showViewer: false,
            backViewer:true,
            wrapperViewer:true,
            protocolVisible: false,
        });
    }
    toogleProtocol (val) {
        this.setState({
            radioChecked: val,
            protocolVisible: false,
        });
    }
    handleLongTap () {
    }
    onPinch () {
    }
    render () {
        const {
            nickName, title, password, radioChecked, passwordVisible, radioVisible,loadingComplete,invalidPass,
            errorMessage, errorMessageVisible, showViewer,backViewer,wrapperViewer,imagelist, protocolVisible,telphone,sharedBy,shareId,nickTitleName,
        } = this.state;
        const radioClassnames = classNames('radio', { on: radioChecked });
        return (
                <div className="fileShare-view" ref={(node) => {
                    this.fileShare = node;
                }}>

                    { backViewer &&
                    <div className="logo-wrapper">
                        <div className="logo-bg">
                            <img src="https://files.pansheng.com/web/bg01.png" alt=""/>
                        </div>
                        <img src="https://files.pansheng.com/web/ps-logo@2x.png" className="logo" alt=""/>
                    </div>
                    }

                    { wrapperViewer &&
                    <div className="share-wrapper">
                        <div className="share">
                            <div className="share-head">
                                <div className="share-title">
                                    <img src="https://files.pansheng.com/web_im/default-icon.png" className="avatar"
                                         alt=""/>
                                    <p className="title">
                                        <span>{nickName}</span> {title}
                                    </p>
                                </div>
                                <img src="https://files.pansheng.com/web/icon-pdf@2x.png" className="icon-pdf" alt=""/>
                            </div>
                            <div className="share-content">
                                {passwordVisible &&
                                <div className="Input-wrapper">
                                    <input
                                        type="number"
                                        value={password}
                                        onChange={e => this.changePassword(e)}
                                    />
                                    <Icon type="lock" style={{color: 'rgba(169, 169, 169, 1)'}}/>
                                </div>
                                }
                                {radioVisible &&
                                <div className="protocol">
                                    <div className={radioClassnames} role="button" tabIndex={0}
                                         onClick={() => this.changeProtocol()}>
                                        <input type="radio" value={radioChecked}/>
                                        <i className="label"/>
                                    </div>
                                    <p>同意磐晟与您签署 <span className="protocol-link" role="button" tabIndex={0}
                                                      onClick={this.handleProtocol}>保密协议</span></p>
                                </div>
                                }
                                <div className="btn" role="button" tabIndex={0} onClick={this.handleView}>
                                    查看文件
                                </div>
                            </div>
                        </div>
                    </div>
                    }

                {errorMessageVisible && <div className="h5-center-box msgAnimation">{errorMessage}</div>}
                <Protocol
                    visible={protocolVisible}
                    toogleProtocol={this.toogleProtocol}
                    radioChecked={radioChecked}
                />
                { showViewer &&
                <div className="image-wrapper">
                    {showViewer && <Application imgList={imagelist} telephone={telphone} nickName={nickName} nickTitleName={nickTitleName} shareId={shareId}
                                                sharedBy={sharedBy}/>}
                </div>
                }
                 { invalidPass &&
                <div>
                    {invalidPass && <InvalidComponet  />}
                </div>
                }
                { loadingComplete &&
                <div>
                    {loadingComplete && <div style={{width: '100%',verticalAlign:'middle',marginTop:'15%'}}><img src="https://files.pansheng.com/img_loading_small.gif" alt=""/>正在加载</div>}
                </div>
                }
            </div>
        );
    }
}

FileShareMobile.propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
};

export default withRouter(FileShareMobile);
